package com.gpjcjl.ui.fragment;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.Nullable;

import com.base.lib.SharedHelper;
import com.gpjcjl.BaseActivity;
import com.gpjcjl.Config;
import com.gpjcjl.R;
import com.gpjcjl.entity.SettingProfile;
import com.yanzhenjie.recyclerview.OnItemClickListener;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 重量测定
 */
public class SettingItem5 extends BaseActivity implements OnItemClickListener {

    @BindView(R.id.listView)
    SwipeRecyclerView listView;
    private CommonAdapter<String> adapter;

    @Override
    protected int getContentView() {
        return R.layout.fragment_item5;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listView.setOnItemClickListener(this);

        List<String> list = new ArrayList<>();
        list.add("录入");
        list.add("自动");
        listView.setAdapter(adapter = new CommonAdapter<String>(mContext, R.layout.item_qphd, list) {
            @Override
            protected void convert(ViewHolder holder, String o, int position) {
                holder.setText(R.id.tv, o);
                String weight = SettingProfile.getWeightType();
                holder.setVisible(R.id.iv, o.equals(weight));
                boolean isAuto = "自动".equals(o) && "自动".equals(weight);
                holder.setVisible(R.id.btnView, isAuto);
                if (isAuto) {
                    EditText editMin = holder.getView(R.id.edit_min);
                    EditText editMax = holder.getView(R.id.edit_max);
                    editMin.setText(SettingProfile.getWeightMin());
                    editMax.setText(SettingProfile.getWeightMax());
                    addWatcher(editMin, Config.DEFAULT_WEIGHT_MIN);
                    addWatcher(editMax, Config.DEFAULT_WEIGHT_MAX);
                }
            }
        });
    }


    private void addWatcher(EditText edit, String key) {
        edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                SharedHelper.getInstance().put(key, s != null ? s.toString() : null);
            }
        });
    }

    @Override
    public void onItemClick(View view, int position) {
        SettingProfile.setWeightType(adapter.getDatas().get(position));
        adapter.notifyDataSetChanged();
    }
}
